<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/24
 * Time: 下午9:29
 */

namespace XmtApp\Modules\Admin\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Resources\OrdersResource;
use App\Tables\Order;

class OrderController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 查询代理用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $query = new Order();
        /**
         * 设置查询条件
         */

        if ($request->filled('created_at') && is_array($request->created_at)) {
            $query = $query->whereBetween('created_at', $request->created_at);
        }

        if ($request->filled('status')) {
            $query = $query->where('status', $request->status);
        }

        if ($request->filled('keyword')) {
            $query = $query->where(function($query) use ($request) {
                $query->orWhere('order_sn', 'like', "%{$request->keyword}%");
                $query->orWhere('device_sn', 'like', "%{$request->keyword}%");

                $query->orWhereHas('agent', function ($query) use ($request) {
                    $query->where('realname', 'like', "%{$request->keyword}%");
                    $query->orWhere('nickname', 'like', "%{$request->keyword}%");
                });
            });
        }

        if ($request->filled('pay_type')) {
            $query = $query->whereHas('payments', function ($query) use ($request) {
                $query->where('pay_mode', $request->pay_type);
            });
        }

        /**
         * 级联查询下级代理
         */
        if ($request->filled('parent_agent_id')) {
            $query = $query->ofChildren($request->parent_agent_id);
        } else {
            if ($this->user->hasRole('agent')) {
                $query = $query->ofChildren($this->user->id);
            }
        }

        $query = $query->orderBy('created_at', 'desc');

        $data = $query->paginate($request->header('pageSize'));

        return new OrdersResource($data);
    }
}